package com.gxa.global.realm;

import com.gxa.mapper.SysRoleMapper;
import com.gxa.mapper.SysUserMapper;
import com.gxa.pojo.Sys_Role;
import com.gxa.pojo.Sys_User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义Realm
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String username = (String)principalCollection.getPrimaryPrincipal();
        Sys_User sys_user = sysUserMapper.findSysUserByUsername(username);
        if(sys_user != null){
            //用户id
            Integer user_id = sys_user.getId();
            List<Sys_Role> sysRoleList = roleMapper.getRoleList(user_id);
            //用户对应的角色
            Set<String> roles = new HashSet<>();
            if(sysRoleList.size() > 0){
                 for (Sys_Role sr : sysRoleList){
                     roles.add(sr.getTitle());
                 }
            }
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.setRoles(roles);
            return info;
        }
        return null;
    }

    //认证 token
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //前端获取的账户
       String username = (String)authenticationToken.getPrincipal();//admin
       String password = (String)authenticationToken.getCredentials();//123456
        //根据前端账户动态查找数据库中的账户信息
        Sys_User sys_user = sysUserMapper.findSysUserByUsername(username);//sys_user admin fdsfdsfdsfdsfdsfdsfsd
        if(sys_user != null && sys_user.getPassword() != null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sys_user.getUsername(),sys_user.getPassword(),"myRealm");
            info.setCredentialsSalt(ByteSource.Util.bytes("GXA"));
            return info;
        }else{
            return null;
        }
    }

}













